import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import penentregsApi from '../../../common/api/food/penentregs.api.js'
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
import doT from '../../../../vendor/template/doT.js';
import { Select2Page } from "../../../common/serve-request.js";


(function (window, document, $) {
    let _vm, getReceveEntry = [], pigDetails = [], pigDetailsInfo = []
    const PartnerSvcUrl = Utils.CurDomain.PartnerSvcUrl;
    const addsaleTemplate = doT.template($('#addpigType-template').text());
    let _pagepurchsOrder= {
        pageSize: 10,
        pageIndex: 0,
        totalPages: -1,
    };
    let _pagepurchsOrderEntry= {
        pageSize: 10,
        pageIndex: 0,
        totalPages: -1,
    };
    let _pageCarWghTkt= {
        pageSize: 10,
        pageIndex: 0,
        totalPages: -1,
    };
    $(function () {
        _vm = new Vue({
            el: "#recevEntries-form",
            data() {
                return {
                    entries: [{
                        "purchsOrderId":'',
                        "purchsOrderNCode": '',
                        "purchsOrderLineNo": '',
                        "suppId": '',
                        "suppNum": '',
                        "suppName": '',
                        "isInternalSupp": '',
                        "breedBatch": '',
                        "breedBatchName": '',
                        "farmOrgObj": {
                            "id": '',
                            "name": ''
                        },
                        "materialObj": {
                            "id": '',
                            "numCode": '',
                            "name": '',
                            "baseMeasureUnit": '',
                            "auxMeasureUnit": ''
                        },
                        "number": '',
                        "weight": '',
                        "price": '',
                        "carNo": '',
                        "carWghTkt":{
                            "id":"",
                            "carNo":"",
                            "netWeight":''
                        },
                        "cfmWeight":'',
                        "cfmAvgWgh":'',
                    }],
                    pagepurchsOrder: { ..._pagepurchsOrder },
                    pagepurchsOrderEntry: { ..._pagepurchsOrderEntry },
                    pageCarWghTkt: { ..._pageCarWghTkt },
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                if (params.isEdit == 'true') {
                    document.title = '入圈登记收货分录 - 编辑'
                }
            },
            methods: {
                // 保存
                submit() {
                    let { purchsOrderNCode, purchsOrderLineNo, materialObj, number, weight, price, carNo, carWghTkt, cfmWeight, cfmAvgWgh } = _vm.entries[0]
                    if (!Utils.IsNotNull(purchsOrderNCode)) {
                        return $.toptip(`请选择采购订单号!`, 'warning');
                    }
                    if (!Utils.IsNotNull(purchsOrderLineNo)) {
                        return $.toptip(`请选择采购行项目号!`, 'warning');
                    }
                    if (!Utils.IsNotNull(materialObj.id)) {
                        return $.toptip(`请选择物料!`, 'warning');
                    }
                    if (number==null||number==undefined||number=='') {
                        return $.toptip(`请输入头数!`, 'warning');
                    }
                    if (weight!=0 &&(weight==null||weight==undefined||weight=='')) {
                        return $.toptip(`请输入发货重量!`, 'warning');
                    }
                    if (cfmWeight!=0 &&(cfmWeight==null||cfmWeight==undefined||cfmWeight=='')) {
                        return $.toptip(`请输入确认重量!`, 'warning');
                    }
                    if (!Utils.IsNotNull(price)) {
                        return $.toptip(`请输入单价!`, 'warning');
                    }
                    if (!Utils.IsNotNull(carNo)) {
                        return $.toptip(`请输入车牌号!`, 'warning');
                    }
                    if (!(/(^[0-9]\d*$)/.test(number))) {
                        return $.toptip(`头数为整数!`, 'warning');
                    }
                    if (!(/^\d+(\.\d{1,2})?$/.test(weight))) {
                        return $.toptip(`发货重量只能保留两位小数!`, 'warning');
                    }
                    if (!(/^\d+(\.\d{1,2})?$/.test(cfmWeight))) {
                        return $.toptip(`确认重量只能保留两位小数!`, 'warning');
                    }
                    if (!(/^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/.test(price))) {
                        return $.toptip(`单价必须大于0并且只能保留两位小数!`, 'warning');
                    }
                    if (!(/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/.test(carNo))) {
                        return $.toptip(`请输入正确的车牌!`, 'warning');
                    }
                    savetips({ ..._vm.entries[0] })
                }
            }
        });
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        _initCommand();
        _initpurchsOrder();
        _initpurchsOrderEntry();
        _initCarWghTkt();

    });

    // 初始化数据
    const _initCommand = async () => {
        getReceveEntry = JSON.parse(Utils.GetSessionStorage("getReceveEntry")) || []
        let isEdit = JSON.parse(getUrlKey('isEdit'))
        let seqId = getUrlKey('index')
        let companyId = getUrlKey('companyId')
        //农厂
        _serviceFarm(companyId, 'farmOrgobjId', '', 'breedBatchId');
        //选择农厂加载养殖批次
        $(`#farmOrgobjId`).on("select2:select", function (e) {
            _vm.entries[0].farmOrgObj.id = $(this).val();
            _vm.entries[0].farmOrgObj.name = $(this).select2('data')[0].text;
            //养殖批次
            _breedBatch('breedBatchId', $(this).val(), '', '请选择养殖批次...');
            let data = e.params.data; // 获取选中项的数据
            let text = data.text; // 获取选中项的文本
            let saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
            $(`#breedBatchId`).prop('disabled', false);
        });
        //养殖批次
        $(`#breedBatchId`).on("select2:select", function (e) {
            _vm.entries[0].breedBatch = $(this).val();
            _vm.entries[0].breedBatchName = $(this).select2('data')[0].text;
            let data = e.params.data; // 获取选中项的数据
            let text = data.text; // 获取选中项的文本
            let saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        });

        //供应商
        _initSAPSuppliers('suppId', '')
        $(`#suppId`).on('select2:select', function (e) {
            _vm.entries[0].suppId = $(this).val();
            _vm.entries[0].suppNum = $(this).val();
            _vm.entries[0].suppName = $(this).select2('data')[0].text;
            let data = e.params.data; // 获取选中项的数据
            let text = data.text; // 获取选中项的文本
            let saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        });

        //物料
        _select2Material('materialId');
        $(`#materialId`).on('select2:select', function (e) {
            _vm.entries[0].materialObj.id = $(this).val();
            _vm.entries[0].materialObj.name = $(this).select2('data')[0].text;
            _vm.entries[0].materialObj.numCode = $(this).select2('data')[0].numCode;
            _vm.entries[0].materialObj.baseMeasureUnit = $(this).select2('data')[0].baseMeasureUnit;
            _vm.entries[0].materialObj.auxMeasureUnit = $(this).select2('data')[0].subMeasureUnit;
            let data = e.params.data; // 获取选中项的数据
            let text = data.text; // 获取选中项的文本
            let saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        });


        // 编辑时赋值
        if (isEdit) {
            let datas = getReceveEntry.find(item => item.seq == seqId)
            const propertiesToCopy = ["purchsOrderId","purchsOrderNCode","purchsOrderLineNo","suppId","suppNum","suppName","isInternalSupp","breedBatch","breedBatchName","farmOrgObj","materialObj","number","weight","price","carNo","carWghTkt","cfmWeight","cfmAvgWgh"];
            propertiesToCopy.reduce((obj, prop) => {
                _vm.entries[0][prop] = datas[prop];
            }, {});
            $(`#suppId`).setSelectValue(_vm.entries[0].suppNum, cutstr(_vm.entries[0].suppName, 20));
            //农厂
            _serviceFarm(companyId, 'farmOrgobjId', _vm.entries[0], 'breedBatchId');
            $(`#materialId`).setSelectValue(_vm.entries[0].materialObj.id, cutstr(_vm.entries[0].materialObj.name, 20));
        }

        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../penentregs/addpenentregs.html?v=${Utils.GetTime()}`;
        });

        // 头数改变计算确认均重
        $(document).on('change', '#number', function () {
            let cfmWeight = Number(_vm.entries[0].cfmWeight);
            let number = Number(_vm.entries[0].number);
            if(cfmWeight && number){
                _vm.entries[0].cfmAvgWgh = Number(cfmWeight/number).toFixed(2);
            }else{
                _vm.entries[0].cfmAvgWgh = 0;
            }
        })

        // 确认重量改变计算确认均重
        $(document).on('change', '#cfmWeight', function () {
            let cfmWeight = Number(_vm.entries[0].cfmWeight);
            let number = Number(_vm.entries[0].number);
            if(cfmWeight && number){
                _vm.entries[0].cfmAvgWgh = Number(cfmWeight/number).toFixed(2);
            }else{
                _vm.entries[0].cfmAvgWgh = 0;
            }
        })

    }

    // 保存提示
    const savetips = (data) => {
        let savetype
        if (Utils.IsNotNull(getUrlKey("isEdit"))) {
            savetype = '修改'
        }
        else {
            savetype = '保存'
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
    				<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
    					<div>是否确认${savetype}该分录？</div>
    				</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        let seq = parseInt(getUrlKey('index'))
                        let isEdit = JSON.parse(getUrlKey('isEdit'))
                        // 新增
                        if (!isEdit) {
                            getReceveEntry.push(data)
                        }
                        // 编辑
                        else if (isEdit) {
                            getReceveEntry[seq] = data
                        }
                        getReceveEntry.map((item, index) => {
                            item.seq = index
                        })
                        // 存入SessionStorage
                        JSON.stringify(Utils.SetSessionStorage("getReceveEntry", getReceveEntry))
                        location.href = `./addpenentregs.html?v=${Utils.GetTime()}`;
                        $.closeModal();
                    }
                }
            ]
        });
    }

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }

    //查询养殖批次
    const _breedBatch = (id, farmId, json, title, tags) => {
        $(`#${id}`).empty();
        $(`#${id}`).prop('disabled', false);
        Select2Page($(`#${id}`), `${Utils.CurDomain.BaseCfgUrl}/breedbatchs/rlist`, (params) => {
            return JSON.stringify({
                farmOrgId: farmId,
                tags: tags,
                name: params.term || '',
                sort: '',
                isEnd: false,
                pageSize: 20,
                pageIndex: (params.page || 1) - 1
            })
        }, "POST", {
            placeholder: title,//默认文字提示
            allowClear: true,//允许清空
            templateResult: function (res) {
                return `${res.name}`;
            }
        });
        if (json) {
            $(`#${id}`).setSelectValue(json.breedBatch, cutstr(json.breedBatchName, 20))
        }
    }

    //获取农厂
    const _serviceFarm = (companyId, id, json, breedBatchId) => {
        penentregsApi.queryTaginfo(companyId, 1, 210).then(res => {
            $(`#${id}`).empty().select2({
                placeholder: '请选择农厂...', //默认文字提示
                language: "zh-CN", //汉化
                allowClear: true, //允许清空
                data: res.map(item => {
                    return {
                        id: item.id,
                        numCode: item.numCode,
                        text: `${item.name}(${item.numCode})`,
                        name: item.name
                    }
                }),
            });
            if (json) {
                $(`#${id}`).setSelectValue(json.farmOrgObj.id, cutstr(json.farmOrgObj.name, 20))
                //养殖批次
                _breedBatch(breedBatchId, json.farmOrgObj.id, json, '请选择养殖批次...');
            } 
            else {
                $(`#${id}`).setSelectValue()
                $(`#${breedBatchId}`).prop('disabled', true);
            }
        });
    }

    const _initSAPSuppliers = (id, json = '') => {
        //获取供应商
        Select2Page($(`#${id}`), `${Utils.CurDomain.SAPSynUrl}/sapsupplier/list`, (params) => {
            return JSON.stringify({
                searchInfo: params.term || '',
                sort: "",
                pageSize: 10,
                pageIndex: (params.page || 1) - 1
            })
        }, "POST", {
            allowClear: true,//允许清空
            placeholder: `请选择供应商...`, //默认文字提示
            templateResult: function (res) {
                return `${res.bU_SORT1}(${res.id})`;
            },
            //下拉框赋值不上解决办法
            templateSelection:function(res){
                return Utils.IsNotNull(res.id)?`${res.bU_SORT1||res.text}(${res.id})`:"";
            },
            ...json,
        });
    }

    //查询物料信息
    const _select2Material = (id) => {
        Select2Page($(`#${id}`), `${Utils.CurDomain.MasterDataUrl}/yymaterials/q`, (params) => {
            return ({
                mgroupid: 'SAP-1',
                // searchinfo: params.term,
                pagesize: 10,
                pageindex: (params.page || 1) - 1,
                ...(Utils.IsNotNull(params.term) ? { searchinfo: params.term } : {})
            })
        }, "GET", {
            allowClear: true,//允许清空
            placeholder: '请选择物料...', //默认文字提示
            templateResult: function (res) {
                // _entriesMatrls = [{ id: "", text: "请选择物料..." }];
                if (Utils.IsNotNull(res.id)) {
                    let sltHtml = {
                        id: res.id,
                        text: res.name,
                        name: res.name,
                        numCode: res.numCode,
                        baseMeasureUnit: res.baseMeasureUnit,
                        subMeasureUnit: res.subMeasureUnit,
                        textString: res.name + "," + res.numCode + "," + res.model + "," + res.baseMeasureUnit,
                        ...res
                    }

                    let sltSpanHtml = "";
                    if (!res.id) {
                        return "";
                    }
                    let arr = sltHtml?.textString?.split(',');
                    if (!arr) return;
                    res.id == -1 ? "" : sltSpanHtml +=
                        `<div style='margin-bottom: 8px;color:#000'>${arr[0]}</div>
                    <label style='font-size:0'>
                    <span style="border: #3e8ef7 1px solid;background-color: #fff;padding : 2px 4px;color:#3e8ef7;font-size: 9px;border-radius: 10px 0 0 10px">${arr[1]}</span>
                    <span style="border: #8A5082 1px solid;background-color: #8A5082;; padding : 2px 4px;color:#fff;font-size: 9px;">${arr[2]}</span>
                    <span style="border: #758EB7 1px solid;background-color: #758EB7;; padding : 2px 4px;color:#fff;font-size: 9px;border-radius: 0 10px 10px 0;">${arr[3]}</span>
                    </label>`;
                    return $(`<span data-code = "${arr[1]}" data-name="${arr[0]}" data-model = "${arr[2]}" data-unit = "${arr[3]}">${sltSpanHtml}</span>`);
                }
            }
        });
        $(`#${id}`).setSelectValue();
    }

    // 初始采购订单
    const _initpurchsOrder = () => {
        // 点击采购订单号 显示选择页面
        $(document).on('click', "#purchsOrderNCode", function () {
            $("#purchsOrder-contact").popup();
            $("#contentpurchsOrder").empty();
            refreshQuerypurchsOrder();
        });
        // 上拉加载
        $("#iscrollpurchsOrder").infinite().on("infinite", function () {
            let _data = _vm.pagepurchsOrder;
            if (_data.pageIndex == _data.totalPages) return;
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                queryListpurchsOrder();
                self.loading = false;
            }, 500);//模拟延迟
        });
        // 搜索
        $("#searchdivpurchsOrder form").submit(function () {
            _mainSearchpurchsOrder();
            return false;
        }).on("input propertychange", Utils.throttle(_mainSearchpurchsOrder, 500));
        searchpurchsOrder();

        // 采购订单 单选框
        $(document).on('click', '#iscrollpurchsOrder .weui-check__label', function (event) {
            event.preventDefault();     //阻止元素发生默认的行为（例如，当点击提交按钮时阻止对表单的提交或者a标签）
            let isChecked = $(this).find("input[type='checkbox']").is(':checked')
            $(this).find("input[type='checkbox']").prop("checked", !isChecked);
            $(this).siblings().find("input[type='checkbox']").prop("checked", false);
            if(!isChecked == true) {
                _vm.entries[0].purchsOrderId = $(this).data("id");
                _vm.entries[0].purchsOrderNCode = $(this).find('.weui-cell__hddata').find('.weui-cell_ebeln').data("id");
                _vm.entries[0].suppId = $(this).find('.weui-cell__hddata').find('.weui-cell_lifnr').data("id");
                _vm.entries[0].suppNum = $(this).find('.weui-cell__hddata').find('.weui-cell_lifnr').data("id");
                _vm.entries[0].isInternalSupp = $(this).find('.weui-cell__hddata').find('.weui-cell_zzsfnb').data("id");
                $.ajax({
                    url: `${Utils.CurDomain.SAPSynUrl}/sapsupplier/${_vm.entries[0].suppNum}`,
                    dataType: 'text',
                    type: 'get',
                    headers: {
                        "Authorization": "Bearer " + Utils.GetSNAuthAT(),
                        "Content-Type": "application/json",
                        "Accept": "application/json"
                    },
                    async: false,
                    success: (res, textStatus, xhr) => {
                        let result = JSON.parse(res);
                        _vm.entries[0].suppName = result.data.bU_SORT1;
                        $(`#suppId`).setSelectValue(_vm.entries[0].suppNum, cutstr(result.data.bU_SORT1, 20) );
                    },
                    error: (xhr, textStatus, error) => {
                        toastr.warning('供应商匹配失败，请自行选择！')
                        $(`#suppId`).setSelectValue();
                        _vm.entries[0].isInternalSupp = '';
                        _vm.entries[0].suppName = '';
                    }
                });
                $.closePopup();
                $('#searchBarpurchsOrder').removeClass("weui-search-bar_focusing");
            }
        });

        // 取消按钮
        $("#cancelpurchsOrder").on('click', function () {
            $.closePopup();
            $('#searchInputpurchsOrder').val("");
            $('#searchBarpurchsOrder').removeClass("weui-search-bar_focusing");
        });
    }

    //查询采购订单信息
    const refreshQuerypurchsOrder = () => {
        let _pagepurchsOrder = {
            searchInfo:$('#searchInputpurchsOrder').val(),
            sort: "ebeln desc",
            pageIndex: 0,
            totalPages: -1,
            pageSize: 50,
        };
        _vm.pagepurchsOrder = Object.assign(_vm.pagepurchsOrder, _pagepurchsOrder);
        queryListpurchsOrder();
    }

    //采购订单 数据源
    const queryListpurchsOrder = () => {
        let _data = _vm.pagepurchsOrder;
        let _list = [];
        penentregsApi.purchOrderList(_data).then(res => {
            let _page = {
                searchInfo:$('#searchInputpurchsOrder').val(),
                sort: "ebeln desc",
                pageSize: 50,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages,
            }
            _vm.pagepurchsOrder = Object.assign({}, _page);
            _list.push(...res.items);
            unique(_list).map(item => {
                let labhtml = `<label class="weui-cell weui-cell_active weui-check__label" for="${item.id}" data-id="${item.id}" id="lab_${item.id}">
                    <div class="weui-cell__hd">
                        <input type="checkbox" class="weui-check" name="checkbox1" id="${item.id}">
                        <i class="weui-icon-checked"></i>
                    </div>
                    <div class="weui-cell__hddata" aria-hidden="true">
                        <span class="weui-cell_ebeln" data-id="${item.ebeln}">采购订单号：${item.ebeln}</span>
                        <div class="weui-cell_lifnr" data-id="${item.lifnr}">供应商编号：${item.lifnr}</div>
                        <div class="weui-cell_zzsfnb" data-id="${item.zzsfnb == 1 ? true : false}">是否内部供应商：${item.zzsfnb == 1 ? '是' : '否'}</div>
                    </div>
                </label>`;
                $("#contentpurchsOrder").append(labhtml);
            });
        });
    }

    // 采购订单 输入框
    const _mainSearchpurchsOrder = function () {
        let _page = {
            searchInfo: $('#searchInputpurchsOrder').val(),
            sort: "ebeln desc",
            pageIndex: 0, 
            totalPages: -1,
            pageSize: 50, 
        };
        _vm.pagepurchsOrder = Object.assign(_vm.pagepurchsOrder, _page);
        $("#contentpurchsOrder").empty();
        queryListpurchsOrder();
    };
    
    // 采购订单 输入框
    const searchpurchsOrder = () => {
        let $searchBar = $('#searchBarpurchsOrder'),
            $searchResult = $('#searchResultpurchsOrder'),
            $searchText = $('#searchTextpurchsOrder'),
            $searchInput = $('#searchInputpurchsOrder'),
            $searchClear = $('#searchClearpurchsOrder'),
            $searchForm = $('#searchFormpurchsOrder'),
            $searchCancel = $('#searchCancelpurchsOrder');

        function hideSearchResult() {
            $searchResult.hide();
            $searchForm.attr('aria-expanded', 'false');
            $searchInput.val('');
        }
        function cancelSearch() {
            hideSearchResult();
            $searchBar.removeClass('weui-search-bar_focusing');
            $searchText.show();
        }

        $searchText.on('click', function () {
            $searchBar.addClass('weui-search-bar_focusing');
            $searchInput.focus();
        });

        $searchInput
            .on('blur', function () {
                if (!this.value.length) cancelSearch();
            })
            .on('input', function () {
                if (this.value.length) {
                    $searchResult.show();
                    $searchForm.attr('aria-expanded', 'true');
                } else {
                    $("#contentpurchsOrder").empty();
                    $searchResult.hide();
                    $searchForm.attr('aria-expanded', 'false');
                }
            });
        $searchClear.on('click', function () {
            hideSearchResult();
            $searchInput.focus();
            $("#contentpurchsOrder").empty();
            refreshQuerypurchsOrder()
        });
        $searchCancel.on('click', function () {
            cancelSearch();
            $("#contentpurchsOrder").empty();
            refreshQuerypurchsOrder();
            $searchInput.blur();
        });
    }

    // 初始采购订单分录
    const _initpurchsOrderEntry = () => {
        // 点击采购行项目号 显示选择页面
        $(document).on('click', "#purchsOdLineNo", function () {
            if (_vm.entries[0].purchsOrderId) {
                $("#purchsOrderEntry-contact").popup();
                $("#contentpurchsOrderEntry").empty();
                refreshQuerypurchsOrderEntry();
            }else{
                $.toptip('请先选择采购订单号', 'warning');
                return;
            }
        });
        // 上拉加载
        $("#iscrollpurchsOrderEntry").infinite().on("infinite", function () {
            let _data = _vm.pagepurchsOrderEntry;
            if (_data.pageIndex == _data.totalPages) return;
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                queryListpurchsOrderEntry();
                self.loading = false;
            }, 500);//模拟延迟
        });

        // 采购订单分录 单选框
        $(document).on('click', '#iscrollpurchsOrderEntry .weui-check__label', function (event) {
            event.preventDefault();     //阻止元素发生默认的行为（例如，当点击提交按钮时阻止对表单的提交或者a标签）
            let isChecked = $(this).find("input[type='checkbox']").is(':checked')
            $(this).find("input[type='checkbox']").prop("checked", !isChecked);
            $(this).siblings().find("input[type='checkbox']").prop("checked", false);
            if(!isChecked == true) {
                _vm.entries[0].purchsOrderLineNo = $(this).find('.weui-cell__hddata').find('.weui-cell_ebelp').data("id");
                let meins= $(this).find('.weui-cell__hddata').find('.weui-cell_meins').data("id");//采购订单单位
                if (meins == "TOU") {
                    _vm.entries[0].number = $(this).find('.weui-cell__hddata').find('.weui-cell_menge').data("id");
                    _vm.entries[0].weight = 0;
                } else if (row.meins == "KG") {
                    _vm.entries[0].number = 0;
                    _vm.entries[0].weight = Number($(this).find('.weui-cell__hddata').find('.weui-cell_menge').data("id")).toFixed(2);
                }
                _vm.entries[0].price = Number($(this).find('.weui-cell__hddata').find('.weui-cell_pbxx').data("id")).toFixed(2);
                // 获取所有物料数据
                penentregsApi.queryMaterial({ MGroupId: 'SAP-1', PageSize: 100000, PageIndex: 0 }).then(res => {
                    let numCode = $(this).find('.weui-cell__hddata').find('.weui-cell_matnr').data("id");
                    _vm.entries[0].materialObj.id = numCode;
                    _vm.entries[0].materialObj.numCode = numCode;
                    _vm.entries[0].materialObj.name = res.items.find(s => s.numCode == numCode)?.name;
                    _vm.entries[0].materialObj.baseMeasureUnit = res.items.find(s => s.numCode == numCode)?.baseMeasureUnit;
                    _vm.entries[0].materialObj.auxMeasureUnit = res.items.find(s => s.numCode == numCode)?.subMeasureUnit;
                    $(`#materialId`).setSelectValue(_vm.entries[0].materialObj.id, cutstr(_vm.entries[0].materialObj.name, 20));
                    $.closePopup();
                    $('#searchBarpurchsOrderEntry').removeClass("weui-search-bar_focusing");
                });
                
            }
        });

        // 取消按钮
        $("#cancelpurchsOrderEntry").on('click', function () {
            $.closePopup();
            $('#searchInputpurchsOrderEntry').val("");
            $('#searchBarpurchsOrderEntry').removeClass("weui-search-bar_focusing");
        });
    }

    //查询采购订单分录信息
    const refreshQuerypurchsOrderEntry = () => {
        let _pagepurchsOrderEntry = {
            pageIndex: 0,
            totalPages: -1,
            pageSize: 50,
        };
        _vm.pagepurchsOrderEntry = Object.assign(_vm.pagepurchsOrderEntry, _pagepurchsOrderEntry);
        queryListpurchsOrderEntry();
    }

    //采购订单分录 数据源
    const queryListpurchsOrderEntry = () => {
        let _data = _vm.pagepurchsOrderEntry;
        let _list = [];
        penentregsApi.getpurchOrder(_vm.entries[0].purchsOrderId).then(res => {
            let _page = {
                pageSize: 50,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages,
            }
            _vm.pagepurchsOrderEntry = Object.assign({}, _page);
            _list.push(...res.item);
            unique(_list).map(item => {
                let labhtml = `<label class="weui-cell weui-cell_active weui-check__label" for="${item.id}" data-id="${item.id}" id="lab_${item.id}">
                    <div class="weui-cell__hd">
                        <input type="checkbox" class="weui-check" name="checkbox1" id="${item.id}">
                        <i class="weui-icon-checked"></i>
                    </div>
                    <div class="weui-cell__hddata" aria-hidden="true">
                        <span class="weui-cell_ebelp" data-id="${item.ebelp}">行项目号：${item.ebelp}</span>
                        <div class="weui-cell_matnr" data-id="${item.matnr}">物料编号：${item.matnr}</div>
                        <div class="weui-cell_menge" data-id="${item.menge}">采购订单数量：${item.menge}</div>
                        <div class="weui-cell_meins" data-id="${item.meins}">采购订单单位：${item.meins}</div>
                        <div class="weui-cell_pbxx" data-id="${item.pbxx}">采购价格：${item.pbxx}</div>
                        <div class="weui-cell_bprme" data-id="${item.bprme}">采购订单价格单位：${item.bprme}</div>
                        <div class="weui-cell_peinh" data-id="${item.peinh}">价格单位：${item.peinh}</div>
                    </div>
                </label>`;
                $("#contentpurchsOrderEntry").append(labhtml);
            });
        });
    }

    // 初始车辆过磅单
    const _initCarWghTkt = () => {
        // 点击净重 显示选择页面
        $(document).on('click', "#netWeight", function () {
            $('#searchInputCarWghTkt').val(_vm.sltrregsCarNo);//筛选条件
            $("#carWghTkt-contact").popup();
            $("#contentCarWghTkt").empty();
            refreshQueryCarWghTkt();
        });
        // 上拉加载
        $("#iscrollCarWghTkt").infinite().on("infinite", function () {
            let _data = _vm.pageCarWghTkt;
            console.log(_data)
            if (_data.pageIndex == _data.totalPages) return;
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                queryListCarWghTkt();
                self.loading = false;
            }, 500);//模拟延迟
        });
        // 搜索
        $("#searchdivCarWghTkt form").submit(function () {
            _mainSearchCarWghTkt();
            return false;
        }).on("input propertychange", Utils.throttle(_mainSearchCarWghTkt, 500));
        searchCarWghTkt();

        // 车辆过磅单 单选框
        $(document).on('click', '#iscrollCarWghTkt .weui-check__label', function (event) {
            // event.stopPropagation();   //表示阻止向父元素冒泡
            event.preventDefault();     //阻止 方法阻止元素发生默认的行为（例如，当点击提交按钮时阻止对表单的提交或者a标签）
            let isChecked = $(this).find("input[type='checkbox']").is(':checked')
            $(this).find("input[type='checkbox']").prop("checked", !isChecked);
            $(this).siblings().find("input[type='checkbox']").prop("checked", false);
            if(!isChecked == true) {
                _vm.entries[0].carWghTkt.id = $(this).data("id");
                _vm.entries[0].carWghTkt.netWeight = $(this).find('.weui-cell__hddata').find('.weui-cell_netWeight').data("id");
                _vm.entries[0].carWghTkt.carNo = $(this).find('.weui-cell__hddata').find('.weui-cell_carNo').data("id");
                $.closePopup();
                $('#searchBarCarWghTkt').removeClass("weui-search-bar_focusing");
            }
        });

        // 取消按钮
        $("#cancelCarWghTkt").on('click', function () {
            $.closePopup();
            $('#searchInputCarWghTkt').val("");
            $('#searchBarCarWghTkt').removeClass("weui-search-bar_focusing");
        });
    }

    //查询车辆过磅单信息
    const refreshQueryCarWghTkt = () => {
        let _pageCarWghTkt = {
            startDate: '1000-01-01',
            endDate: '9999-12-31',
            billNo: '',
            billStatus: '',
            customerName: '',
            carType: 0,
            carNo: $('#searchInputCarWghTkt').val(),
            sort: "bizFormObj.createTime desc",
            pageIndex: 0,
            totalPages: -1,
            pageSize: 50,
        };
        _vm.pageCarWghTkt = Object.assign(_vm.pageCarWghTkt, _pageCarWghTkt);
        queryListCarWghTkt();
    }

    //车辆过磅单 数据源
    const queryListCarWghTkt = () => {
        let _data = _vm.pageCarWghTkt;
        let _list = [];
        penentregsApi.postCarWghTktList(_data).then(res => {
            let _page = {
                startDate: '1000-01-01',
                endDate: '9999-12-31',
                billNo: '',
                billStatus: '',
                customerName: '',
                carType: 0,
                carNo: $('#searchInputCarWghTkt').val(),
                sort: "bizFormObj.createTime desc",
                pageSize: 50,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages,
            }
            _vm.pageCarWghTkt = Object.assign({}, _page);
            _list.push(...res.items);
            unique(_list).map(item => {
                let labhtml = `<label class="weui-cell weui-cell_active weui-check__label" for="${item.id}" data-id="${item.id}" id="lab_${item.id}">
                    <div class="weui-cell__hd">
                        <input type="checkbox" class="weui-check" name="checkbox1" id="${item.id}">
                        <i class="weui-icon-checked"></i>
                    </div>
                    <div class="weui-cell__hddata" aria-hidden="true">
                        <span class="weui-cell_billNo" data-id="${item.bizFormObj.billNo}">单据编号：${item.bizFormObj.billNo}</span>
                        <div class="weui-cell_carNo" data-id="${item.carNo}">车牌号：${item.carNo}</div>
                        <div class="weui-cell_netWeight" data-id="${item.netWeight}">净重：${item.netWeight}</div>
                    </div>
                </label>`;
                $("#contentCarWghTkt").append(labhtml);
            });
        });
    }

    // 车辆过磅单 输入框
    const _mainSearchCarWghTkt = function () {
        let _page = {
            startDate: '1000-01-01',
            endDate: '9999-12-31',
            billNo: '',
            billStatus: '',
            customerName: '',
            carType: 0,
            carNo: $('#searchInputCarWghTkt').val(),
            sort: "bizFormObj.createTime desc",
            pageIndex: 0, 
            totalPages: -1,
            pageSize: 50, 
        };
        _vm.pageCarWghTkt = Object.assign(_vm.pageCarWghTkt, _page);
        $("#contentCarWghTkt").empty();
        queryListCarWghTkt();
    };
    
    // 车辆过磅单 输入框
    const searchCarWghTkt = () => {
        let $searchBar = $('#searchBarCarWghTkt'),
            $searchResult = $('#searchResultCarWghTkt'),
            $searchText = $('#searchTextCarWghTkt'),
            $searchInput = $('#searchInputCarWghTkt'),
            $searchClear = $('#searchClearCarWghTkt'),
            $searchForm = $('#searchFormCarWghTkt'),
            $searchCancel = $('#searchCancelCarWghTkt');

        function hideSearchResult() {
            $searchResult.hide();
            $searchForm.attr('aria-expanded', 'false');
            $searchInput.val('');
        }
        function cancelSearch() {
            hideSearchResult();
            $searchBar.removeClass('weui-search-bar_focusing');
            $searchText.show();
        }

        $searchText.on('click', function () {
            $searchBar.addClass('weui-search-bar_focusing');
            $searchInput.focus();
        });

        $searchInput
            .on('blur', function () {
                if (!this.value.length) cancelSearch();
            })
            .on('input', function () {
                if (this.value.length) {
                    $searchResult.show();
                    $searchForm.attr('aria-expanded', 'true');
                } else {
                    $("#contentCarWghTkt").empty();
                    $searchResult.hide();
                    $searchForm.attr('aria-expanded', 'false');
                }
            });
        $searchClear.on('click', function () {
            hideSearchResult();
            $searchInput.focus();
            $("#contentCarWghTkt").empty();
            refreshQueryCarWghTkt()
        });
        $searchCancel.on('click', function () {
            cancelSearch();
            $("#contentCarWghTkt").empty();
            refreshQueryCarWghTkt();
            $searchInput.blur();
        });
    }

    function unique(arr) {
        const res = new Map();
        return JSON.parse(JSON.stringify(arr)).filter((a) => !res.has(a.id) && res.set(a.id, 1))
    }


})(window, document, jQuery)